<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------


namespace app\adminapi\controller;


use app\adminapi\controller\BaseAdminController;
use app\adminapi\lists\HuanxinLists;
use app\adminapi\logic\HuanxinLogic;
use app\adminapi\validate\HuanxinValidate;
use app\common\exception\AppLogicException;
use app\common\model\Huanxin;
use app\common\service\ExcelImporter;
use app\common\service\UploadService;
use PhpOffice\PhpSpreadsheet\Exception;


/**
 * Huanxin控制器
 * Class HuanxinController
 * @package app\adminapi\controller
 */
class HuanxinController extends BaseAdminController
{


    /**
     * @notes 获取列表
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/03/07 16:57
     */
    public function lists()
    {
        return $this->dataLists(new HuanxinLists());
    }


    /**
     * @notes 添加
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/03/07 16:57
     */
    public function add()
    {
        $params = (new HuanxinValidate())->post()->goCheck('add');
        $result = HuanxinLogic::add($params);
        if (true === $result) {
            return $this->success('添加成功', [], 1, 1);
        }
        return $this->fail(HuanxinLogic::getError());
    }


    /**
     * @notes 编辑
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/03/07 16:57
     */
    public function edit()
    {
        $params = (new HuanxinValidate())->post()->goCheck('edit');
        $result = HuanxinLogic::edit($params);
        if (true === $result) {
            return $this->success('编辑成功', [], 1, 1);
        }
        return $this->fail(HuanxinLogic::getError());
    }


    /**
     * @notes 删除
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/03/07 16:57
     */
    public function delete()
    {
        $params = (new HuanxinValidate())->post()->goCheck('delete');
        HuanxinLogic::delete($params);
        return $this->success('删除成功', [], 1, 1);
    }


    /**
     * @notes 获取详情
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/03/07 16:57
     */
    public function detail()
    {
        $params = (new HuanxinValidate())->goCheck('detail');
        $result = HuanxinLogic::detail($params);
        return $this->data($result);
    }


    public function import()
    {
        $headerMapping = [
            'titles' => [
                '分类',
                '品牌',
                '机型',
                '内存',
                '换新价',
                '延保',
                '电池',
                '碎屏',

            ],
            'fields' => [
                '分类'   => ['type'],
                '品牌'   => ['brand'],
                '机型'   => ['spec'],
                '内存'   => ['disk'],
                '换新价' => ['huanxin_money'],
                '延保'   => ['yanbao_money'],
                '电池' => ['dianchi_money'],
                '碎屏' => ['suiping_money'],
            ]
        ];
        // 上传文件
        $result = UploadService::file(0);

        $filePath = $result['url'];

        // 创建 ExcelImporter 实例
        try {
            $excelImporter = new ExcelImporter($filePath);// 设置标题映射
            $excelImporter->setHeaderMapping($headerMapping);// 解析 Excel 数据
            $data = $excelImporter->parse();
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        } catch (AppLogicException $e) {
            return $this->fail($e->getMessage());
        }
        $returnList = [
            'normal' => [],
            'error'  => []
        ];
        collect($data)->each(function ($item) use (&$returnList) {
            $res = Huanxin::where('spec', $item['spec'])->where('disk', $item['disk'])->find();
            if ($res) {
                $item['error_msg'] ='该机器已配置';
                $returnList['error'][] = $item;
            }else{
                $returnList['normal'][] = $item;
            }
        });


        return $this->success('导入成功', $returnList, 1, 1);
    }


    public function sureimport()
    {
        $data = $this->request->post();
        collect($data)->each(function ($item)  {
            $res = Huanxin::where('spec', $item['spec'])->where('disk', $item['disk'])->find();
            if (!$res) {
                $item['type'] = match ($item['type']) {
                    '手机' => 'phone',
                    '平板' => 'pad',

                    default => 1,
                };;
                Huanxin::create($item);
            }
        });
        return $this->success('导入成功', [], 1, 1);
    }




}